<?php 
namespace Admin\Model;
use Think\Model;
//用户模型
class MemberModel extends Model{

	protected $_validate = array(
     array('username','require','用户名不能为空'), 
     array('username','','用户名称已经存在！',0,'unique',1), 
     array('phone','require','手机号不能为空'), 
     array('email', '/^[\w\-\.]+@[\w\-\.]+(\.\w+)+$/', '邮箱格式错误！', 2, 'regex')
   );

	protected $_auto = array ( 
         array('password','md5',3,'function') , 
         array('create_time','time',1,'function'), // 对update_time字段在更新的时候写入当前时间戳
     );

	public function check_login($data){
		$data['password'] = md5($data['password']);
		$user = $this->where(array('username'=>$data['username']))->find();
		if(!$user){$this->error='用户名不存在';return false;}
		if($user['status'] == 1){$this->error='账号被禁用';return false;}
		if($user['password'] != $data['password']){$this->error='密码错误';return false;}
		$user = array('userid'=>$user['id'],'username'=>$user['username']);
		session('user',$user);
		return true; 
	}


	//增加 修改
	public function  update(){
		$data = $this->create();
		if(empty($data)) return false;
		if(strlen($data['username']) < 6){
			$this->error = '用户名最少6个长度';
			return false;
		}

		if(!preg_match('/^(13|15|17)\d{9}$/',$data['phone'])){
			$this->error = '手机格式不正确';
			return false;
		}

		if(empty($data['id'])) {
			if(!empty($data['p1']) && $data['p1'] != 1)  {
				$data = array_merge($data,$this->getMember($data['p1']));
			}

			$data['agentid'] = $this->agentid();
			$id = $this->add($data);
			if(!$id) {
				$this->error = '添加失败';
				return false;
			}

		} else {
			if(empty(I('post.password'))) unset($data['password']);
				$res = $this->save($data);
				if($res === flase){
					return false; 
				}
			}

			return $data;
		}

	//查询 上级 上上级
	public function getMember($id=null){
		$id = $this->where(['id'=>$id])->getField('p1');
		if($id){
			$data['p2'] = $this->where(['id'=>$id])->getfield('p1');
		}

		if($data['p2']){
			$data['p3'] = $this->where(['id'=>$data['p2']])->getfield('p1');
		}

		return $data;
	}



    //代理号
    public  function agentid(){
       $id = M()->query('select top 1 * from web_member order by id desc');
       return $id[0]['agentid']+1;
    }
}
